import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:syn_4s/core/extension/build_context_extension.dart';
import 'package:syn_4s/core/extension/int_extension.dart';
import 'package:syn_4s/core/model/gas_model.dart';
import 'package:syn_4s/core/utils/date_format_utils.dart';
import 'package:syn_4s/core/viewmodel/main_view_model.dart';
import 'package:syn_4s/ui/shared/app_theme.dart';

import 'custom_ui.dart';
import 'main_fold.dart';

class MainGasMonitoring extends StatefulWidget {
  final Key? scrollKey;
  final MainViewModel viewModel;
  final String? title;

  const MainGasMonitoring(
      {super.key, required this.viewModel, this.scrollKey, this.title});

  @override
  State<MainGasMonitoring> createState() => _MainGasMonitoringState();
}

class _MainGasMonitoringState extends State<MainGasMonitoring> {
  final ScrollController _controller = ScrollController();

  @override
  void initState() {
    super.initState();
    addScrollListener(_controller, widget.viewModel.isGasScrollable);

    debounce(widget.viewModel.gasKeyword, (_) {
      widget.viewModel.getGasMonitoring();
    }, time: const Duration(milliseconds: 300));
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MainFold(
      scrollKey: widget.scrollKey,
      title: widget.title ?? context.l10n.gas_monitoring,
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.only(left: 8.px, right: 40.px, top: 4.px),
            height: 38.px,
            child: TextField(
              focusNode: widget.viewModel.myFocusNode,
              onChanged: (value) {
                print("onChanged:$value");
                widget.viewModel.gasKeyword.value = value;
              },
              style: TextStyle(fontSize: 15.px),
              decoration: InputDecoration(
                  contentPadding: EdgeInsets.symmetric(horizontal: 10.px),
                  filled: true,
                  fillColor: Colors.white,
                  hintText: context.l10n.search_hint,
                  enabledBorder: getWhiteOvalBorder(radius: 50.px),
                  focusedBorder: getWhiteOvalBorder(radius: 50.px),
                  suffixIcon: Icon(
                    Icons.search,
                    size: 22.px,
                  )),
            ),
          ),
          Container(
            margin: EdgeInsets.symmetric(horizontal: 8.px, vertical: 6.px),
            height: 240,
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Column(
                children: [
                  buildTitle(context),
                  Expanded(
                    child: Obx(() => SingleChildScrollView(
                          controller: _controller,
                          physics: widget.viewModel.isGasScrollable.value
                              ? const AlwaysScrollableScrollPhysics()
                              : const NeverScrollableScrollPhysics(),
                          child: Column(
                            children: List.generate(
                                widget.viewModel.gasMonitoring.length, (index) {
                              return buildContent(
                                  widget.viewModel.gasMonitoring[index]);
                            }),
                          ),
                        )),
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget buildTitle(BuildContext context) {
    return Row(
      children: [
        buildTitleBox(context.l10n.device),
        buildTitleBox(context.l10n.co),
        buildTitleBox(context.l10n.h2s),
        buildTitleBox(context.l10n.o2),
        buildTitleBox(context.l10n.ch4),
        buildTitleBox(context.l10n.water_level,
            width: 116.px, margin: EdgeInsets.zero),
      ],
    );
  }

  Widget buildTitleBox(String data,
      {double? width, EdgeInsetsGeometry? margin}) {
    return Container(
      margin: margin ?? EdgeInsets.only(right: 1.px),
      width: width ?? 74.px,
      height: 40.px,
      alignment: Alignment.center,
      color: AppTheme.yellowColor,
      child: Text(
        data,
        textAlign: TextAlign.center,
        style: const TextStyle(color: AppTheme.infoTextColors),
      ),
    );
  }

  Widget buildContent(GasMonitoring value) {
    return IntrinsicHeight(
      child: Container(
        color: Colors.white,
        child: Row(
          children: [
            buildDeviceBox(value.deviceName ?? ""),
            buildDivider(),
            buildData(value, 0, "ppm"),
            buildDivider(),
            buildData(value, 1, "ppm"),
            buildDivider(),
            buildData(value, 2, "%"),
            buildDivider(),
            buildData(value, 3, "%"),
            buildDivider(),
            buildData(value, 4, "m", width: 116.px),
          ],
        ),
      ),
    );
  }

  buildData(GasMonitoring value, int index, String unit, {double? width}) {
    if (index >= (value.gass?.length ?? 0)) {
      return const Text("-");
    }
    return buildDataBox(
        "${value.gass?[index].val}$unit",
        DateFormatUtils.dateTimeToStr(value.gass?[index].portalAt,
            format: "dd-MM-yyyy\nHH:mm:dd"),
        width: width);
  }

  Widget buildDivider() {
    return Container(
      color: AppTheme.backgroundColors,
      width: 1.px,
    );
  }

  Widget buildContentBox({double? width, Widget? child}) {
    return Container(
        padding: EdgeInsets.symmetric(horizontal: 2.px),
        width: width ?? 74.px,
        alignment: Alignment.center,
        child: child);
  }

  Widget buildDeviceBox(String data, {double? width}) {
    return buildContentBox(
        width: width,
        child:
            Text(data, style: const TextStyle(color: AppTheme.infoTextColors)));
  }

  Widget buildDataBox(String data, String time, {double? width}) {
    return buildContentBox(
        width: width ?? 74.px,
        child: Column(
          children: [
            Text(
              data,
              style: TextStyle(
                  fontSize: 16.px,
                  color: AppTheme.orangeColor,
                  fontWeight: FontWeight.w900),
            ),
            Text(
              time,
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 13.px, color: AppTheme.infoTextColors),
            ),
          ],
        ));
  }
}
